/// <reference types="node" />
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import viteCompression from 'vite-plugin-compression'
import viteImagemin from 'vite-plugin-imagemin'

const addPrefixPlugin = (prefix: string) => ({
  name: 'add-prefix-plugin',
  async transformIndexHtml(html: string){
    return html.replace(/(href|src)="(?!http|\/\/)/g, `$1="${prefix}`)
  }
})

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    // Gzip compression for built assets
    viteCompression({ algorithm: 'gzip' }),
    // Brotli compression for built assets (served when supported by the browser)
    viteCompression({ algorithm: 'brotliCompress', ext: '.br' }),
    // Image optimization for jpeg and png assets
    viteImagemin({
      mozjpeg: {
        quality: 75,
      },
      pngquant: {
        quality: [0.65, 0.8],
        speed: 4,
      },
      svgo: {
        plugins: [
          { name: 'removeViewBox', active: false },
          { name: 'removeEmptyAttrs', active: false },
        ],
      },
    }),
    addPrefixPlugin('/edu'),
  ],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
    },
  },
  server: {
    port: 3000,
    open: true,
  },
  build: {
    target: 'es2019',
    sourcemap: false,
    chunkSizeWarningLimit: 1500,
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return id
              .toString()
              .split('node_modules/')[1]
              .split('/')[0]
              .toString()
          }
        },
      },
    },
  },
})